package com.clearliang.nativeapp.plugins;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.clearliang.nativeapp.view.GlobalParam;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.StandardMethodCodec;
import io.flutter.view.FlutterView;

/**
 * Created by ClearLiang on 2019/6/4
 * Description：
 * Function :
 */
public class MethodPlugin implements MethodChannel.MethodCallHandler {
    /**
     * 通道名称、函数名、参数名
     */
    public final static String CHANNEL = "com.liang.flutter.plugin/method";
    public final static String ACTION_LOG = "showLog";
    public final static String ACTION_TOAST = "showToast";
    public final static String ACTION_START = "startActivity";
    public final static String LOG_ARGUMENT = "data";

    static MethodChannel channel;

    private Context context;

    private MethodPlugin(Context context) {
        this.context = context;
    }

    public static void registerWith(FlutterView flutterView) {
        channel = new MethodChannel(flutterView, CHANNEL, StandardMethodCodec.INSTANCE);
        MethodPlugin instance = new MethodPlugin(flutterView.getContext());
        channel.setMethodCallHandler(instance);
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        switch (methodCall.method) {
            case ACTION_LOG:
                String text = methodCall.argument(LOG_ARGUMENT);
                if (TextUtils.isEmpty(text)) {
                    result.error("Data is Null", null, null);
                } else {
                    Log.e("Method信息:", "" + text);
                    result.success("Show Log is ok");
                }
                break;
            case ACTION_TOAST:
                String msg = methodCall.argument(LOG_ARGUMENT);
                if (TextUtils.isEmpty(msg)) {
                    result.error("Data is Null", null, null);
                } else {
                    Toast.makeText(context, "" + msg, Toast.LENGTH_LONG).show();
                    result.success("Show Toast is ok");
                }
                break;
            case ACTION_START:
                String activityName = methodCall.argument(LOG_ARGUMENT);
                startActivity(activityName);
                result.success("Start Activity is ok");
                break;
            default:
                result.notImplemented();
                break;
        }

    }

    private void startActivity(String activityName) {
        Intent intent = new Intent(GlobalParam.ActivityAction + activityName);
        context.startActivity(intent);
    }
}
